package br.indt.framework.threadpool;

import br.indt.framework.log.MicrologWrapper;


public class ThreadPoolWorker extends Thread {
	
	private static final MicrologWrapper log = MicrologWrapper.getLogger(ThreadPoolWorker.class);

	private boolean stop = false;
	private PriorityQueue priorityQueue = null;
	private ThreadPoolTask currentTask = null;
	
	public ThreadPoolWorker(PriorityQueue priorityQueue, String name) {
		super(name);
		this.priorityQueue = priorityQueue;
		start();
	}
	
	public ThreadPoolTask getCurrentTask() {
		return currentTask;
	}

	public void run() 
	{
		while (!stop) {
			try {
				
				currentTask = (ThreadPoolTask) priorityQueue.getItem();

				if (currentTask != null) {
					currentTask.execute();
					Thread.sleep(100);					
				} else {
					
					synchronized (priorityQueue) {		
						priorityQueue.wait();
					}
					
				}
				
			} catch (Exception ex) {
				log.error(ex.getMessage());
			}
		}
	}
	
	public void stop() {
		stop = true;
		
		if(currentTask != null) {
			currentTask.cancel();
		}
		
		try{ interrupt(); } catch (Exception e) { }
	}
}
